package com.example.demo.socket;

import com.example.demo.game.fiveState;

import java.awt.*;

public class FiveGameService {
    private static final int BOARD_SIZE = 15;
    private int[][] board;
    private int currentPlayer = 1; // 1 代表黑子，2 代表白子
    private boolean gameOver = false;

    public FiveGameService() {
        initBoard();
    }

    private void initBoard() {
        board = new int[BOARD_SIZE][BOARD_SIZE];
    }

    public void changeDirection(Point move) {
        if (!gameOver && isValidMove(move)) {
            int x = (int) move.getX();
            int y = (int) move.getY();
            board[x][y] = currentPlayer;
            if (checkWin(x, y)) {
                gameOver = true;
            } else {
                currentPlayer = 3 - currentPlayer; // 切换玩家
            }
        }
    }

    private boolean isValidMove(Point move) {
        int x = (int) move.getX();
        int y = (int) move.getY();
        return x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE && board[x][y] == 0;
    }

    private boolean checkWin(int x, int y) {
        int[][] directions = {{1, 0}, {0, 1}, {1, 1}, {1, -1}};
        for (int[] dir : directions) {
            int count = 1;
            // 正向检查
            for (int i = 1; i < 5; i++) {
                int newX = x + i * dir[0];
                int newY = y + i * dir[1];
                if (newX >= 0 && newX < BOARD_SIZE && newY >= 0 && newY < BOARD_SIZE && board[newX][newY] == currentPlayer) {
                    count++;
                } else {
                    break;
                }
            }
            // 反向检查
            for (int i = 1; i < 5; i++) {
                int newX = x - i * dir[0];
                int newY = y - i * dir[1];
                if (newX >= 0 && newX < BOARD_SIZE && newY >= 0 && newY < BOARD_SIZE && board[newX][newY] == currentPlayer) {
                    count++;
                } else {
                    break;
                }
            }
            if (count >= 5) {
                return true;
            }
        }
        return false;
    }

    public fiveState getState() {
        return new fiveState(null, gameOver);
    }

    public void reset() {
        initBoard();
        currentPlayer = 1;
        gameOver = false;
    }
}